package com.chen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.chen.common.MyExpection;
import com.chen.common.Result;

import com.chen.convert.DeptConvert;
import com.chen.pojo.DeptDO;
import com.chen.mapper.DeptMapper;
import com.chen.service.IDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.vo.dept.DeptCreateReqVO;
import com.chen.vo.dept.DeptRespVO;
import com.chen.vo.dept.DeptUpdateReqVO;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.chen.constants.ErrorCodeConstants.DEPT_NAME_NOT_UNIQUE;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author chen
 * @since 2024-04-10
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, DeptDO> implements IDeptService {
    @Resource
    public DeptMapper deptMapper;


    /**
     * 获取部门列表
     *
     * @return
     */
    @Override
    public Result getDeptList() {
        //获取部门列表
        List<DeptDO> deptDOList = deptMapper.selectList(null);
        //转化响应格式
        List<DeptRespVO> deptRespVOList = DeptConvert.INSTANCE.convertList01(deptDOList);
        //返回数据
        return Result.success(deptRespVOList);

    }

    /**
     * 根据id删除部门
     * @param id
     * @return
     */
    @Override
    public Result deleteDeptById(int id) {
        //删除数据
        int result = deptMapper.deleteById(id);
        //判断是否删除成功
        //1.删除失败
        if(result==0){
            return Result.success(false);
        }
        //2.删除成功
        return Result.success(true);
    }

    /**
     * 创建部门
     * @param reqVO
     * @return
     */
    @Override
    public Result createDept(DeptCreateReqVO reqVO) {
        //判断名字有没有重复
        validateNameUnique(reqVO.getName(),null);
        //数据转化
        DeptDO deptDO = DeptConvert.INSTANCE.convert01(reqVO);

        //插入
        deptMapper.insert(deptDO);
        //返回
        return  Result.success();
    }

    /**
     * 根据id查找部门
     * @param id
     * @return
     */
    @Override
    public Result getDeptById(int id) {
      return  Result.success(deptMapper.selectById(id));
    }

    @Override
    public Result updateDept(DeptUpdateReqVO reqVO) {
        //判断名字是不是重复了
        validateNameUnique(reqVO.getName(),reqVO.getId());
        //数据转化
       DeptDO deptDO= DeptConvert.INSTANCE.convert01(reqVO);
       //更新
        deptMapper.updateById(deptDO);
        //返回
        return Result.success(true);
    }

    @SneakyThrows
    private void validateNameUnique(String name,Integer id)  {

        DeptDO deptDO = deptMapper.selectDeptByName(name);
        //判空
        if(ObjectUtil.isNotNull(deptDO)&&!deptDO.equals(id)){
            throw new MyExpection(DEPT_NAME_NOT_UNIQUE);
        }
    }
}
